<?php

namespace app\controller\adminapi\system;

use think\App;
use think\Request;
use app\common\model\user\UserGroup;
use hiduoke\controller\BaseController;


/**
 * 菜单管理
 * @package app\controller\adminapi\setting
 * User: liuhongbin
 * Date: 2021-05-15 19:54
 */
class Menu extends BaseController
{
    /**
     * @var \app\common\model\system\Menu
     */
    public $MenuModel;

    public function __construct(App $app)
    {
        $this->MenuModel = new \app\common\model\system\Menu();
        parent::__construct($app);
    }

    /**
     * 显示资源列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOption()
    {
        $data = [];
        $list = $this->MenuModel->where([])->order("sort asc")->select()->toArray();
        foreach ($list as $value) {
            $option = array(
                "label"     => $value['menu_name'],
                "pid"       => $value["pid"],
                "value"     => $value["id"],
                "id"        => $value['id'],
                'menu_type' => $value['menu_type'],
                'is_show'   => $value['is_show']
            );
            $data[$value['id']] = $option;
        }
        return $this->success('ok', get_tree_children($data));
    }

    public function getList()
    {
        $list = $this->MenuModel->where([])->order("sort asc")->select()->toArray();
        return $this->success('', get_tree_children($list));
    }


    public function getMenus()
    {
        $UserGroupModel = new UserGroup();
        $group_id = $this->userInfo['group_id'];
        $user_group = $UserGroupModel->where(['id' => $group_id])->find();
        if ($user_group) {
            $where = [['menu_type', '=', 1], ['is_show', '=', 1]];
            if (!$this->auth->isFounder()) {
                $where[] = ['id', 'in', (array)$user_group['rules']];
            }
            $list = $this->MenuModel->where($where)->order("sort asc")->select()->toArray();
            foreach ($list as $value) {
                $option = array(
                    "pid"       => $value["pid"],
                    "value"     => $value["id"],
                    "id"        => $value['id'],
                    "path"      => $value['menu_path'],
                    "meta"      => [
                        "icon"  => $value['icon'],
                        "title" => $value['menu_name']
                    ],
                    'menu_type' => $value['menu_type']
                );
                $data[$value['id']] = $option;
            }
        } else {
            $data = [];
        }
        return $this->success('ok', get_tree_children($data));
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $formData = $request->post("formData");
        if ($formData['menu_type'] == 1) {
            if (!$formData['menu_name'] || !$formData['menu_path']) {
                return $this->error("菜单名称或者路由地址不能为空");
            }

            if (!$formData['auth_mark']) {
                return $this->error("权限标识不能为空");
            }
        } else {
            if (!$formData['menu_name'] || !$formData['api_url']) {
                return $this->error("接口名称或者接口地址不能为空");
            }
            if (!$formData['methods']) {
                return $this->error("请求方式不能为空");
            }
        }
        $this->MenuModel->save($formData);
        return $this->success("新增成功");
    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read($id)
    {
        if (!$id) {
            return $this->error("菜单不存在");
        }
        $data = $this->MenuModel->where(['id' => $id])->find();
        if (!$data) {
            return $this->error("菜单不存在");
        }
        return $this->success("ok", $data);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //

    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        if (!$id) {
            return $this->error("菜单不存在");
        }
        $data = $this->MenuModel->where(['id' => $id])->find();
        if (!$data) {
            return $this->error("菜单不存在");
        }
        $formData = $request->post('formData');
        if ($formData['id'] === $formData['pid']) {
            return $this->error("父级分类不得选择自己");
        }
        $data->save($formData);
        return $this->success("修改成功");
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $children = $this->MenuModel->where(['pid' => $id])->find();
        if (!$children) {
            $menu = $this->MenuModel->where(['id' => $id])->find();
            if (!$menu) {
                return $this->success("删除失败，菜单不存在");
            }
            $this->MenuModel->where(['id' => $id])->delete();
            return $this->success("删除成功");
        } else {
            return $this->error("请先删除子节点菜单");
        }
    }
}
